/*
 * @Author: xiaosihan
 * @Date: 2024-06-23 19:54:36
 * @Last Modified by: xiaosihan
 * @Last Modified time: 2024-08-18 03:56:40
 */

//Group
import { Group } from "three";
import HeadPortraitLable from "./HeadPortraitLable";
import { autorun } from "mobx";
import partCollaborateStore from "../../partCollaborateStore";
import partCollaborateDemoStore from "@views/pc/PartCollaborateDemo/partCollaborateDemoStore";

// 头像标签组
export default class HeadPortraitGroup extends Group {
  constructor() {
    super();
  }

  declare children: HeadPortraitLable[];

  //颜色数组
  colors = ["#05D67B", "#5503FA", "#FA6419"];

  getColor(i: number) {
    return this.colors[i % 3];
  }

  userColorMap = new Map<string, string>();

  setDatas() {}

  // 获取子子元素
  getChildren(i: number) {
    let lable = this.children[i];
    if (!lable) {
      lable = new HeadPortraitLable();
      lable.userData = {
        cursor: "pointer",
        enableEvent: true,
      };
      lable.addEventListener("click", (e) => {
        partCollaborateStore.setSelectLableId(lable.uuid);
      });
      this.add(lable);
    }
    return lable;
  }

  dispose = autorun(() => {
    const isDemo = location.hash === "#/partCollaborateDemo";
    const { partLableDatas } = isDemo
      ? partCollaborateDemoStore
      : partCollaborateStore;
    const { blastDirection, blastProgress, selectLableId } =
      partCollaborateStore;

    const lableDatas = partLableDatas
      .filter((l) => l.location)
      .map((l) => {
        const partLable = JSON.parse(l.location);
        return {
          id: l.id,
          userId: l.userId,
          x: partLable.x,
          y: partLable.y,
          z: partLable.z,
          modelIndex: partLable.modelIndex,
        };
      });

    this.children.map((o) => (o.visible = false));

    this.userColorMap.clear();

    // 遍历对象和数据
    for (let i = 0; i < lableDatas.length; i++) {
      const lableData = lableDatas[i];
      const lable = this.getChildren(i);
      const { id, x, y, z, modelIndex } = lableData;

      lable.originPosition.set(x, y, z);
      lable.meshIndex = modelIndex;
      if (blastDirection[modelIndex]) {
        const { x: X, y: Y, z: Z } = blastDirection[modelIndex];
        lable.position
          .set(X, Y, Z)
          .multiplyScalar(blastProgress)
          .add(lable.originPosition);
      } else {
        lable.position.set(x, y, z);
      }
      lable.text = String(lableDatas.length - i);
      if (!this.userColorMap.has(lableData.userId)) {
        this.userColorMap.set(
          lableData.userId,
          this.getColor(this.userColorMap.size)
        );
      }
      lable.color = this.userColorMap.get(lableData.userId)!;

      lable.active = selectLableId === id;
      lable.uuid = id;
      lable.visible = true;
    }
  });

  updateMatrix(): void {
    super.updateMatrix();
  }
}
